package com.linciping.plugin.base;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.actions.CodeInsightAction;
import com.intellij.lang.ContextAwareActionHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.psi.KtFile;

public class BaseKotlinGenerateAction extends CodeInsightAction {

    private CodeInsightActionHandler codeInsightActionHandler;

    public BaseKotlinGenerateAction() {
    }

    public BaseKotlinGenerateAction(CodeInsightActionHandler codeInsightActionHandler) {
        this.codeInsightActionHandler = codeInsightActionHandler;
    }

    @NotNull
    @Override
    protected CodeInsightActionHandler getHandler() {
        return codeInsightActionHandler;
    }

    @Override
    protected void update(@NotNull Presentation presentation, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, @NotNull DataContext dataContext, @Nullable String actionPlace) {
        super.update(presentation, project, editor, file, dataContext, actionPlace);
        if (codeInsightActionHandler instanceof ContextAwareActionHandler && presentation.isEnabled()) {
            presentation.setEnabled(((ContextAwareActionHandler) codeInsightActionHandler).isAvailableForQuickList(editor, file, dataContext));
        }
    }

    @Override
    protected void update(@NotNull Presentation presentation, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
        presentation.setEnabledAndVisible(isValidForFile(project, editor, file));
    }

    @Override
    protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
        if (!(file instanceof KtFile)) return false;
        if (file instanceof PsiCompiledElement) return false;
        final KtFile ktFile = (KtFile) file;
        return isValidForKtFile(ktFile, editor);
    }

    protected boolean isValidForKtFile(final KtFile ktFile, Editor editor) {
        return true;
    }
}
